package br.unifesp.lma.chamada.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import br.unifesp.lma.chamada.dao.ProfessorDAO;
import br.unifesp.lma.chamada.model.entity.Professor;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@RequestMapping("/")
@Controller
public class LoginController {

	@Autowired
	private ProfessorDAO	professorDAO;

	@RequestMapping("/login")
	public String login(String url) {

		UserService userService = UserServiceFactory.getUserService();
		return "redirect:" + userService.createLoginURL("/login-retorno?url=" + (url == null || url.isEmpty() ? "/" : url));
	}

	@RequestMapping("/logout")
	public String logout(HttpSession httpSession) {

		httpSession.invalidate();
		UserService userService = UserServiceFactory.getUserService();
		return "redirect:" + userService.createLogoutURL("/");
	}

	@RequestMapping("/login-retorno")
	public String loginRetorno(HttpSession httpSession, String url) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		Professor professor = professorDAO.getByEmail(user.getEmail());

		if (professor == null) {
			professor = new Professor();
			professor.setNome(user.getNickname());
			professor.setEmail(user.getEmail());
		}
		
		professor.setAdmin(userService.isUserAdmin());
		professorDAO.put(professor);
		
		httpSession.setAttribute("professorId", professor.getId());
		httpSession.setAttribute("professor", professor);
		return "redirect:" + url;
	}
}
